package com.zqxq.lottery.service.sys.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.common.utils.DateUtils;
import com.zqxq.common.utils.DispatcherUtils;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.config.YmlConfig;
import com.zqxq.lottery.entity.bo.sys.AddSysActivityBO;
import com.zqxq.lottery.entity.bo.sys.SysActivityBO;
import com.zqxq.lottery.entity.bo.sys.SysCouponBO;
import com.zqxq.lottery.entity.enums.ActivityIdEnum;
import com.zqxq.lottery.entity.po.order.UserOrderPO;
import com.zqxq.lottery.entity.po.sys.LotteryHnumPO;
import com.zqxq.lottery.entity.po.sys.SysActivityPO;
import com.zqxq.lottery.entity.po.sys.SysConfigPO;
import com.zqxq.lottery.entity.po.sys.SysCouponPO;
import com.zqxq.lottery.entity.po.user.*;
import com.zqxq.lottery.entity.vo.order.UserOrderVO;
import com.zqxq.lottery.mapper.order.UserOrderMapper;
import com.zqxq.lottery.mapper.sys.LotteryHnumMapper;
import com.zqxq.lottery.mapper.sys.SysActivityMapper;
import com.zqxq.lottery.mapper.sys.SysConfigMapper;
import com.zqxq.lottery.mapper.sys.SysCouponMapper;
import com.zqxq.lottery.mapper.user.*;
import com.zqxq.lottery.service.order.IUserOrderService;
import com.zqxq.lottery.service.sys.ISysActivityService;
import com.zqxq.lottery.service.user.IUserCashService;
import com.zqxq.lottery.service.user.IUserCouponService;
import com.zqxq.lottery.service.user.IUserWindowMsgService;
import com.zqxq.lottery.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 苦智
 * @date 2018/5/23 13:52
 * @description
 * @ClassName SysActivityServiceImpl
 */
@Service
@Slf4j
public class SysActivityServiceImpl extends ServiceImpl<SysActivityMapper,SysActivityPO> implements ISysActivityService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public static String url = "http://h5.zhanguo.fun/reg/add-land.html?user_id=";

    public static Map<String,Object> map = new HashMap<String,Object>(){{
        put("11","双色球");put("12","福彩3D");put("14","大乐透");put("15","七星彩");put("16","排列三");put("21","竞猜足球");}};

    @Autowired
    private UserFundsMapper userFundsMapper;
    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private IUserCashService userCashService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserActivityMapper userActivityMapper;
    @Autowired
    private UserInviteMapper userInviteMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private SysCouponMapper sysCouponMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private IUserOrderService userOrderService;
    @Autowired
    private LotteryHnumMapper lotteryHnumMapper;
    @Autowired
    private IUserCouponService userCouponService;
    @Autowired
    private UserAgentMapper userAgentMapper;
    @Autowired
    private SysActivityMapper sysActivityMapper;
    @Autowired
    private IUserWindowMsgService userWindowMsgService;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Transactional
    @Override
    public boolean saveUserActivity(SysActivityBO bo) {
        boolean flag = false;
        if (bo == null || bo.getActivityId() == null)
            return flag;
        if (bo.getActivityId().equals(ActivityIdEnum.INVITE_ORDER.getId()) && (bo.getInviterId() == null || bo.getOrderId() == null))
            return false;
        try {
            //查询活动对应的优惠券
            SysCouponPO sysCouponPO = new SysCouponPO();
            sysCouponPO.setActivity_id(bo.getActivityId());
            sysCouponPO.setStatus(1);
            List<SysCouponPO> sysCouponPOList = sysCouponMapper.selectCoupon(sysCouponPO);
            if (sysCouponPOList.size() < 1)
                return false;
            //用户信息
            UserInfoPO userInfoPO = userInfoMapper.selectById(bo.getUserId());
            if (bo.getActivityId().equals(ActivityIdEnum.INVITE_ORDER.getId())
                    ||bo.getActivityId().equals(ActivityIdEnum.RECHARGE_ORDER.getId())
                    ||bo.getActivityId().equals(ActivityIdEnum.RECHARGE_500_ORDER.getId())
                    ||bo.getActivityId().equals(ActivityIdEnum.RECHARGE_1000_ORDER.getId())
                    ||bo.getActivityId().equals(ActivityIdEnum.FIRST_INVITE_REGISTER_REWARD.getId())
                    ||bo.getActivityId().equals(ActivityIdEnum.FIRST_TODAY_INVITE_REGISTER_REWARD.getId())
                    ){
                userInfoPO = userInfoMapper.selectById(bo.getInviterId());
            }
            int orderStatus = 0;
            ActivityIdEnum e = ActivityIdEnum.getEnumById(bo.getActivityId());
            BigDecimal money = new BigDecimal(0);
            if (sysCouponPOList.size() > 0 && sysCouponPOList.get(0).getMoney() != null){
                money = sysCouponPOList.get(0).getMoney();
            }
            BigDecimal cmoney = sysCouponPOList.get(0).getCondition_money();//后台配置的条件金额
            if (bo.getConditionMoney() != null){
                if (bo.getConditionMoney().compareTo(cmoney) < 0){
                    return false;
                }
            }
            SysConfigPO sysConfigPO = sysConfigMapper.getByKey("INVITATION_TYPE");
            Integer invitationType = Integer.valueOf(sysConfigPO.getCval());
            switch (e) {
                case REGISTER:
                    //注册奖励优惠券，一个设备号只能一次
                    Wrapper wrapper = new EntityWrapper();
                    wrapper.eq("equipment_id",userInfoPO.getEquipment_id());
                    Integer count = userInfoMapper.selectCount(wrapper);
                    if(sysCouponPOList.size()>0 && count<2){
                        //第一版新用户注册有奖活动
                        saveUserCash(money,userInfoPO,7,"新用户注册平台赠送资金",null);
                        userWindowMsgService.saveUserMsg(userInfoPO.getId(),"新用户奖励", String.valueOf(money.intValue()),5);
                        flag = true;
                    }
                    break;
                case ORDER_LOST_PRIZE:
                    //用户首单未中奖奖励
                    orderStatus = 1;
                    saveUserCash(money,userInfoPO,7,"首单未中奖奖励",null);
                    flag = true;
                    break;
                case RECHARGE:
                    if (bo.getConditionMoney().compareTo(sysCouponPOList.get(0).getCondition_money()) == -1)
                        break;
                    saveUserCash(money,userInfoPO,7,"充值奖励",null);
                    flag = true;
                    break;
                case INVITE_ORDER:
                    //邀请用户首次下单奖励
                    userInfoPO = userInfoMapper.selectById(bo.getInviterId());
                    saveUserCash(money, userInfoPO, 7, "邀请用户首次下单奖励",bo.getUserId());
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"新增好友首次下单",String.valueOf(money.intValue()),2);
                    flag = true;
                    break;
                case RECHARGE_ORDER:
                    //邀请用户首充值奖励
                    userInfoPO = userInfoMapper.selectById(bo.getInviterId());
                    if(invitationType==0) {
                        //赠送趣豆
                        saveUserCash(money, userInfoPO, 7, "邀请用户首充值奖励", bo.getUserId());
                        userWindowMsgService.saveUserMsg(userInfoPO.getId(), "新增好友首次充值", String.valueOf(money.intValue()), 3);
                    }else{
                        //赠送钻石
                        saveUserZSCash(money.divide(new BigDecimal(100)), userInfoPO, 8, "邀请用户首充值奖励", bo.getUserId());
                        userWindowMsgService.saveUserMsg(userInfoPO.getId(), "新增好友首次充值", String.valueOf(money.intValue()/100), 3);
                    }
                    flag = true;
                    break;
                case RECHARGE_500_ORDER:
                    //邀请用户累积充值奖励
                    userInfoPO = userInfoMapper.selectById(bo.getInviterId());
                    if(invitationType==0) {
                        //赠送趣豆
                        saveUserCash(money, userInfoPO, 7, "邀请用户累积充值500奖励", bo.getUserId());
                        userWindowMsgService.saveUserMsg(userInfoPO.getId(), "好友累计充值500元", String.valueOf(money.intValue()), 3);
                    }else {
                        //赠送钻石
                        saveUserZSCash(money.divide(new BigDecimal(100)), userInfoPO, 8, "邀请用户累积充值500奖励", bo.getUserId());
                        userWindowMsgService.saveUserMsg(userInfoPO.getId(), "好友累计充值500元", String.valueOf(money.intValue()/100), 3);
                    }
                    flag = true;
                    break;
                case RECHARGE_1000_ORDER:
                    //邀请用户累积充值奖励
                    userInfoPO = userInfoMapper.selectById(bo.getInviterId());
                    if(invitationType==0) {
                        //赠送趣豆
                        saveUserCash(money, userInfoPO, 7, "邀请用户累积充值1000奖励", bo.getUserId());
                        userWindowMsgService.saveUserMsg(userInfoPO.getId(), "好友累计充值1000元", String.valueOf(money.intValue()), 3);
                    }else {
                        //赠送钻石
                        saveUserZSCash(money.divide(new BigDecimal(100)), userInfoPO, 8, "邀请用户累积充值1000奖励", bo.getUserId());
                        userWindowMsgService.saveUserMsg(userInfoPO.getId(), "好友累计充值1000元", String.valueOf(money.intValue()/100), 3);
                    }
                    flag = true;
                    break;
                case LOGIN:
                    //新用户首次登录优惠券派发
                    saveUserCoupon(userInfoPO,sysCouponPOList);
                    break;
                case FIRST_ORDER_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户首次参与竞猜奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"首次参与竞猜", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_RECHARGE_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户首次充值奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"首次充值", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_WIN_ORDER_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户首次中奖奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"首次中奖", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_INVITE_REGISTER_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户首次邀请好友注册奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"首次邀请好友注册", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日参与竞猜奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日参与竞猜", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_5_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日参与5次竞猜奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日参与5次竞猜", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_FIRST_WIN_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日首次中奖奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日首次中奖", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_WIN_3_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日中奖3次奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日中奖3次", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_FOOTBALL_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日下单竞猜足球奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日下单竞猜足球", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_GUESSBALL_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日下单欢乐猜球奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日下单欢乐猜球", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_ELECTRIC_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日下单电竞竞猜奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日下单电竞竞猜", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_20RMB_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日下单满20元奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日下单满20元", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_50RMB_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日下单满50元奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日下单满50元", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_ORDER_100RMB_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户今日下单满100元奖励",null);
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"今日下单满100元", String.valueOf(money.intValue()),3);
                    break;
                case FIRST_TODAY_INVITE_REGISTER_REWARD:
                    saveUserCash(money,userInfoPO,7,"用户新增好友注册奖励",bo.getUserId());
                    userWindowMsgService.saveUserMsg(userInfoPO.getId(),"新增好友注册", String.valueOf(money.intValue()),3);
                    break;
            }
            if (flag) {
                //保存用户活动表
                UserActivityPO userActivityPO = new UserActivityPO();
                userActivityPO.setId(ymlConfig.getPkId());
                userActivityPO.setActivity_id(bo.getActivityId());
                userActivityPO.setUser_id(userInfoPO.getId());
                userActivityPO.setStatus(1);
                userActivityPO.setOrder_id(bo.getOrderId());
                userActivityPO.setOrder_status(orderStatus);
                userActivityMapper.insert(userActivityPO);
            }
        }catch (Exception e){
            log.error("活动错误",e);
        }
        return flag;
    }

    private void saveUserCash(BigDecimal money, UserInfoPO userInfoPO,Integer payWay,String info,Long orderId) {
        UserFundsPO fundsPO = userFundsMapper.selectById(userInfoPO.getId());
        boolean f = false;
        if(null == fundsPO){
            fundsPO = new UserFundsPO();
            fundsPO.setUser_id(userInfoPO.getId());
            fundsPO.setLot_bean(BigDecimal.ZERO);
            f = true;
        }
        fundsPO.setLot_bean(fundsPO.getLot_bean().add(money));

        UserCashPO userCashPO = new UserCashPO();
        userCashPO.setId(ymlConfig.getPkId());
        userCashPO.setUser_id(userInfoPO.getId());
        userCashPO.setReal_name(userInfoPO.getReal_name());
        userCashPO.setMobile(userInfoPO.getMobile());
        userCashPO.setPay_way(payWay);
        userCashPO.setPay_account("ZQXQ");
        userCashPO.setType(7);
        userCashPO.setStatus(4);
        userCashPO.setPay_amount(money);
        userCashPO.setInfo(info);
        userCashPO.setOrder_id(orderId);
        userCashService.insert(userCashPO);
        fundsPO.setBonus_status(1);

        if(f){
            userFundsMapper.insert(fundsPO);
        }
        else{
            fundsPO.setCreate_time(null);
            fundsPO.setUpdate_time(null);
            userFundsMapper.updateById(fundsPO);
        }
    }

    private void saveUserZSCash(BigDecimal money, UserInfoPO userInfoPO,Integer payWay,String info,Long orderId) {
        UserFundsPO fundsPO = userFundsMapper.selectById(userInfoPO.getId());
        boolean f = false;
        if(null == fundsPO){
            fundsPO = new UserFundsPO();
            fundsPO.setUser_id(userInfoPO.getId());
            fundsPO.setLot_bean(BigDecimal.ZERO);
            f = true;
        }
        fundsPO.setDiamonds(fundsPO.getDiamonds().add(money));
        UserCashPO userCashPO = new UserCashPO();
        userCashPO.setId(ymlConfig.getPkId());
        userCashPO.setUser_id(userInfoPO.getId());
        userCashPO.setReal_name(userInfoPO.getReal_name());
        userCashPO.setMobile(userInfoPO.getMobile());
        userCashPO.setPay_way(payWay);
        userCashPO.setPay_account("ZQXQ");
        userCashPO.setType(7);
        userCashPO.setStatus(4);
        userCashPO.setPay_amount(money);
        userCashPO.setInfo(info);
        userCashPO.setOrder_id(orderId);
        userCashService.insert(userCashPO);
        fundsPO.setBonus_status(1);

        if(f){
            userFundsMapper.insert(fundsPO);
        }
        else{
            fundsPO.setCreate_time(null);
            fundsPO.setUpdate_time(null);
            userFundsMapper.updateById(fundsPO);
        }
    }

    //领取优惠券公共方法
    @Transactional
    public void saveUserCoupon(UserInfoPO po, List<SysCouponPO> sysCouponPOS) {
        String key = "PUSH_USER_COUPON" + po.getId();
        String value = stringRedisTemplate.opsForValue().get(key);
        List<UserCouponPO> list = new ArrayList<>();
        try {
            if (StrUtils.isEmpty(value)) {
                stringRedisTemplate.opsForValue().set(key,key);
                for (SysCouponPO sysCouponPO : sysCouponPOS) {
                    Long couponId = sysCouponPO.getId();
                    int status = 0;
                    if (sysCouponPO.getDelay_days() > 0)
                        status = 3;
                    addUserCoupon(po.getId(),couponId,sysCouponPO.getDelay_days(),sysCouponPO.getValidity_days(),status,list);
                }
                //批量插入
                userCouponService.insertBatch(list);
            }
        } catch (Exception e) {
            log.error("发放失败：" + e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
        } finally {
            stringRedisTemplate.delete(key);
        }
    }

    private void addUserCoupon(Long userId,Long couponId,Integer addDay,Integer validityDay,Integer status,List<UserCouponPO> list) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",userId);
        wrapper.eq("coupon_id",couponId);
        Integer count = userCouponMapper.selectCount(wrapper);
        if(count==0){
            UserCouponPO userCouponPO = new UserCouponPO();
            userCouponPO.setId(ymlConfig.getPkId());
            userCouponPO.setCoupon_id(couponId);
            userCouponPO.setUser_id(userId);
            Date a = DateUtil.dateFormat(DateUtils.addDay(new Date(),addDay),"yyyy-MM-dd");
            userCouponPO.setStart_time(DateUtil.dateFormat(DateUtils.addDay(new Date(),addDay),"yyyy-MM-dd"));
            userCouponPO.setDistribute_time(DateUtil.dateFormat(DateUtils.addDay(new Date(),addDay),"yyyy-MM-dd"));
            if (validityDay > 0)
                userCouponPO.setEnd_time(DateUtil.dateFormat(DateUtils.addDay(new Date(),addDay+validityDay),"yyyy-MM-dd"));
            userCouponPO.setStatus(status);
            list.add(userCouponPO);
        }
    }
    //用户邀请收益统计
    @Override
    public Map<String, Object> queryUserActivityStatistic(Long userId) {
        UserAgentPO userAgentPO = userAgentMapper.selectAgentById(userId);
        Map<String,Object> inviteData = new HashMap<>();
        //添加邀请链接
        inviteData.put("inviteUrl",url+userId);
        //如果是代理商则区别统计
        if (userAgentPO != null){
            String createTime = DateUtils.dateToStr(userAgentPO.getCreate_time(),"yyyy-MM-dd HH:mm:ss");
            String comTime = DateUtils.dateToStr(userAgentPO.getCommissions_time(),"yyyy-MM-dd HH:mm:ss");
            inviteData = userInviteMapper.queryAgentData(userId,createTime,comTime);
            Map<String,Object> m = userInviteMapper.queryAgentRegNum(userId,createTime);
            inviteData.putAll(m);
            return inviteData;
        }
        inviteData = userInviteMapper.queryInviteData(userId);
        return inviteData;
    }

    /**
    * @Author 苦智
    * @Description 用户优惠券展示
    * @Date 17:07 2018/5/24
    * @Param [userId]
    * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
    **/
    @Override
    public Page<Map<String,Object>> queryUserCouponList(Long userId, Integer status,Integer pageNo,Integer pageSize) {
        Page<Map<String,Object>> page = new Page<>(pageNo,pageSize);
        List<Map<String,Object>> couponList = userCouponMapper.queryUserCouponList(page,userId,status);
        if (couponList == null || couponList.size()< 1){
            return page;
        }
        for (Map<String, Object> map : couponList) {
            if (map.get("lotteryId") != null){
                String lotteryId = map.get("lotteryId").toString();
                map.put("lotteryName",getNameById(lotteryId));
                if (lotteryId.equals("ALL")){
                    //所有彩种直接跳转首页
                    map.put("lotteryStatus",0);
                } else {
                    //单个或多个彩种就默认跳转第一个彩种
                    String[] lotteryIds = lotteryId.split(",");
                    LotteryHnumPO topOpenOne = lotteryHnumMapper.getTopOne(Long.parseLong(lotteryIds[0]));
                    map.put("lotteryStatus",lotteryIds[0]);
                    if (topOpenOne != null){
                        map.put("period",topOpenOne.getPeriod());
                    }
                }
            }
        }
        page.setRecords(couponList);
        return page;
    }

    private static String getNameById(String lotteryId){
        String lotteryName = "";
        if (!StrUtils.isEmpty(lotteryId)){
            if ("ALL".equals(lotteryId)){
                lotteryName = "全部彩种";
            } else {
                String[] lotterys = lotteryId.split(",");
                List<String> list = new ArrayList();
                for (String lottery : lotterys) {
                    list.add(map.get(lottery).toString());
                }
                lotteryName = StringUtils.join(list.toArray(),",");
            }

        }
        return lotteryName;
    }

    @Override
    public List<Map<String,Object>> getAvailableCouponList(Long orderId) {
        List<Map<String,Object>> returnList = new ArrayList<>();
        Page<Map<String,Object>> page = new Page<>(1,1000);
        try {
            UserOrderVO userOrderVO = userOrderService.get(orderId);
            List<Map<String,Object>> couponList = userCouponMapper.queryUserCouponList(page, Long.valueOf(userOrderVO.getUserId()),1);
            String orderLotteryId = userOrderVO.getLotteryId();
            for (Map<String, Object> map : couponList) {
                boolean usable = true;
                //满减金额限定
                Double conditionMoney = DispatcherUtils.parseDouble(map.get("conditionMoney"));
                Double orderMoney = DispatcherUtils.parseDouble(userOrderVO.getPayAmount());
                if(orderMoney<conditionMoney){
                    usable = false;
                }
                //彩种限定
                String lotteryId = String.valueOf(map.get("lotteryId"));
                map.put("lotteryName",getNameById(lotteryId));
                if(!lotteryId.equals("ALL")){
                    if(!lotteryId.contains(orderLotteryId)){
                        usable = false;
                    }
                }
                if (lotteryId.split(",").length > 1 || lotteryId.equals("ALL")){
                    //多个彩种
                    map.put("lotteryStatus",2);
                } else {
                    map.put("lotteryStatus",1);
                }
                if(usable){
                    returnList.add(map);
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnList;
    }

    //支付优惠券抵扣
    @Transactional
    @Override
    public Map<String,Object> saveCouponConsume(Long couponId, Long orderId) {
        UserOrderPO userOrderPO = userOrderMapper.selectById(orderId);
        if (userOrderPO == null || userOrderPO.getStatus() != 0) {
            return null;
        }
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put("lotteryId",userOrderPO.getLottery_id());    //彩种
        returnMap.put("period",userOrderPO.getPeriod());    //期号
        BigDecimal money = userOrderPO.getPay_amount();
        returnMap.put("orderMoney",userOrderPO.getPay_amount());    //订单金额
        UserInfoPO userInfoPO = userInfoMapper.selectById(userOrderPO.getUser_id());
        if (userInfoPO == null) {
            return null;
        }
        SysCouponPO sysCouponPO = sysCouponMapper.selectById(couponId);
        BigDecimal couponMoney = BigDecimal.ZERO;
        if(sysCouponPO!=null){
            couponMoney = sysCouponPO.getMoney();
        }
        returnMap.put("couponMoney",couponMoney);    //优惠券抵扣
        Map<String,Object> userFunds = userFundsMapper.getById(userOrderPO.getUser_id());
        BigDecimal balance = (BigDecimal) userFunds.get("balance"); //中奖金额
        BigDecimal bonus = (BigDecimal) userFunds.get("bonus"); //充值金额
        BigDecimal letBean = (BigDecimal) userFunds.get("lotBean"); //奖励金额
        BigDecimal subTotal = balance.add(bonus).add(letBean).setScale(2,BigDecimal.ROUND_DOWN);
        if(couponMoney.compareTo(BigDecimal.ZERO)==1){
            money = money.subtract(couponMoney);
        }
        if(money.compareTo(BigDecimal.ZERO)==1){
            //如果优惠券抵扣后还需支付大于0，则进行余额抵扣
            if(money.compareTo(subTotal)==-1){
                //余额够抵扣
                returnMap.put("subBalanceMoney",money);
                returnMap.put("finalMoney",BigDecimal.ZERO);
            }else{
                //余额不够抵扣
                returnMap.put("subBalanceMoney",subTotal);
                money = money.subtract(subTotal);
                returnMap.put("finalMoney",money);
            }
        }else{
            returnMap.put("subBalanceMoney",BigDecimal.ZERO);
            returnMap.put("finalMoney",BigDecimal.ZERO);
        }
        returnMap.put("availableCouponSize",getAvailableCouponList(orderId).size());
        returnMap.put("availableCouponList",getAvailableCouponList(orderId));
        returnMap.put("couponId",couponId);
        returnMap.put("orderId",orderId);
        return returnMap;
    }

    @Override
    public Page querySysActivity(Map<String,Object> paramMap) {
        Page<Map<String,Object>> page = new Page<>(DispatcherUtils.parseInt(paramMap.get("pageNo")),DispatcherUtils.parseInt(paramMap.get("pageSize")));
        List<Map<String,Object>> resultList = baseMapper.querySysActivity(page,paramMap);
        page.setRecords(resultList);
        return page;
    }

    @Override
    public AddSysActivityBO saveSysActivity(AddSysActivityBO bo) {
        String id = bo.getId();
        if (!StringUtils.isEmpty(id)) {
            baseMapper.updateSysActivity(bo);
        }else{
            baseMapper.saveSysActivity(bo);
        }
        return bo;
    }

    @Override
    public void deleteSysActivity(String activityId) {
        baseMapper.deleteSysActivity(activityId);
    }

    @Override
    public SysCouponBO saveSysCoupon(SysCouponBO bo) {
        String id = bo.getId();
        if (!StringUtils.isEmpty(id)) {
            baseMapper.updateSysCoupon(bo);
        }else{
            int amount = bo.getAmount();
            for(int i=0;i<amount;i++){
                baseMapper.saveSysCoupon(bo);
            }
        }
        return bo;
    }

    @Override
    public void deleteSysCoupon(String couponId) {
        baseMapper.deleteSysCoupon(couponId);
    }

    @Override
    public Page querySysCoupon(Map<String, Object> paramMap) {
        Page<Map<String,Object>> page = new Page<>(DispatcherUtils.parseInt(paramMap.get("pageNo")),DispatcherUtils.parseInt(paramMap.get("pageSize")));
        List<Map<String,Object>> resultList = baseMapper.querySysCoupon(page,paramMap);
        page.setRecords(resultList);
        return page;
    }

    @Override
    public void acceptingCoupon() {
        baseMapper.updateUserCoupon();
    }

    @Override
    public void updateCouponUsed(Long userId, Long couponId) {
        baseMapper.updateCouponUsed(userId,couponId);
    }

    /**
    * @Author 苦智
    * @Description 用户邀请排行榜
    * @Date 16:33 2018/6/21
    * @Param []
    * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
    **/
    @Override
    public Map<String, Object> getInviteRankData() {
        Map<String,Object> resultMap = new HashMap<>();
        //代理商
        String agentIds = userAgentMapper.selectAgentList();
        SysCouponPO sysCouponPO = sysCouponMapper.selectByActivityId(2L);
        List<Map<String, Object>> moneyList = baseMapper.getInviteRankMoney(agentIds);
//        resultMap.put("countList",countList);
        resultMap.put("moneyList",moneyList);
        return resultMap;
    }

}
